package com.shxc.smarttrade.old.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapter.FollowCancelListAdapter;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.FollowMasterListInfo;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.MyFootView;
import com.shxc.smarttrade.old.myview.MyRefreshHeadView;
import com.shxc.smarttrade.old.myview.RecycleViewDivider;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/9/29.
 */

public class FollowCancelListFragment extends Fragment {
    @BindView(R.id.ll_nodata_bg)
    AutoLinearLayout llNodataBg;
    @BindView(R.id.x_recycler_view)
    XRecyclerView xRecyclerView;
    private View rootView;
    @BindView(R.id.tv_explain_text)
    TextView tvExplain;
    private LinearLayoutManager manager;
    private int page = 1;
    private OrderSupervisorFragment parentFragment;
    private FollowCancelListAdapter adapter;
    private boolean isRefresh = false;//xRecycleView是否在刷新中

    private List<FollowMasterListInfo.DataBean.MasterBean> allList = new ArrayList<>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (xRecyclerView != null)
                        xRecyclerView.refreshComplete();
                    if (isRefresh) {
                        allList.clear();
                        adapter.notifyDataSetChanged();
                    }
                    List<FollowMasterListInfo.DataBean.MasterBean> mbList = (List<FollowMasterListInfo.DataBean.MasterBean>) msg.obj;
                    if (mbList != null && mbList.size() != 0) {
                        allList.addAll(mbList);
                        adapter.setDatas(allList);
                    } else {
                        if (xRecyclerView != null)
                            xRecyclerView.setNoMore(true);
                        if (allList.size() != 0)
                            parentFragment.showMyToasts("已加载全部！");
                    }
                    if (allList.size() == 0)
                        llNodataBg.setVisibility(View.VISIBLE);
                    else
                        llNodataBg.setVisibility(View.GONE);
                    isRefresh = false;
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_super_man, null);
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null)
            parent.removeView(rootView);
        ButterKnife.bind(this, rootView);
        initView();
        allList.clear();
        initData();
        initListener();
        return rootView;
    }


    private void initView() {
        EventBus.getDefault().register(this);

        tvExplain.setText("没有数据");
        parentFragment = (OrderSupervisorFragment) getParentFragment();

        manager = new LinearLayoutManager(getContext());
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayout.VERTICAL, 2, getResources().getColor(R.color.all_background)));
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        MyRefreshHeadView myRefreshHeadView = new MyRefreshHeadView(getContext());
        myRefreshHeadView.setArrowImageView(R.mipmap.indicator_arrow);
        xRecyclerView.setRefreshHeader(myRefreshHeadView);
        xRecyclerView.setFootView(new MyFootView(getContext()));
        xRecyclerView.setAdapter(adapter = new FollowCancelListAdapter(getContext()));
    }

    private void initData() {
        Map<String, Object> map = new HashMap<>();
        if (getActivity() != null)
            map.put("accessToken", SpUtils.getString(getActivity(), "accessToken", ""));
        map.put("userId", String.valueOf(SpUtils.getInt(getActivity(), "userId", -1)));
        map.put("status", String.valueOf(2));
        map.put("page", String.valueOf(page));
        map.put("pageSize", String.valueOf(10));
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.FOLLOW_MASTER_NOW_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                if (xRecyclerView != null)
                    xRecyclerView.refreshComplete();
                MyApplication.showToast(getActivity(), "网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response == null || new JsonParser().parse(response).isJsonNull()) {
                    return;
                }
                Gson gson = new Gson();
                FollowMasterListInfo fmli = gson.fromJson(response, FollowMasterListInfo.class);
                if (fmli.getErr_code().equals("0")) {
                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = fmli.getData().getMaster();
                    handler.sendMessage(msg);

                } else {
                    parentFragment.showMyToasts(fmli.getErr_msg());
                }
            }
        });
    }

    private void initListener() {
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefresh = true;
                        page = 1;
                        initData();
                    }
                }, 1000);

            }

            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initData();
                    }
                }, 1000);

            }
        });
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.FOLLOW_ORDER_DETAIL_ACTIVITY)) {
            page = 1;
            isRefresh = true;
            initData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
